package org.testile.datasetmanipulation;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import org.apache.commons.lang.Validate;
import org.dbunit.dataset.IDataSet;
import org.testile.dataset.scriptable.ScriptableDataSet;
import org.testile.dataset.scriptable.ScriptableDataSetConfig;
import org.testile.dataset.sqlscript.SqlScriptEngine;

/**
 *
 * @author hvizmar
 */
public class SQLEngineWrapper implements DatasetWrapper {
	private String driverName;
	private String url;
	private String username;
	private String password;

	public SQLEngineWrapper(String driverName, String url, String username, String password) {
		Validate.notEmpty(driverName, "Driver name cannot be empty.");
		Validate.notEmpty(url, "URL cannot be empty.");
		Validate.notEmpty(username, "Username cannot be empty.");
		Validate.notEmpty(password, "Password cannot be empty.");

		this.driverName = driverName;
		this.url = url;
		this.username = username;
		this.password = password;
	}

	@Override
	public IDataSet wrap(IDataSet dataSet) {
		Connection connection = getConnection(driverName, url, username, password);
		Bindings bindings = bindingWithConnection(connection);
		ScriptableDataSetConfig sqlConfig = new ScriptableDataSetConfig("sql", "SQL:", bindings);
		ScriptableDataSet sqlDataSet = new ScriptableDataSet(dataSet, sqlConfig);

		return sqlDataSet;
	}

	private Bindings bindingWithConnection(Connection connection) {
		SimpleBindings sqlBinding = new SimpleBindings();
		sqlBinding.put(SqlScriptEngine.DB_CONNECTION, connection);
		return sqlBinding;
	}

	private Connection getConnection(String driver, String url, String user, String password) {
		try {
			Class.forName(driver);
			return DriverManager.getConnection(url, user, password);
		} catch (SQLException ex) {
			throw new IllegalStateException("Could not create database connection", ex);
		} catch (ClassNotFoundException ex) {
			throw new IllegalStateException("Could not create database connection", ex);
		}
	}
}
